package fr.sedoo.metadata.client.ui.widget.field.impl;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import fr.sedoo.commons.client.util.ElementUtil;
import fr.sedoo.commons.client.util.StringUtil;
import fr.sedoo.metadata.client.message.MetadataMessage;
import fr.sedoo.metadata.client.ui.label.StatusLabelProvider;
import fr.sedoo.metadata.client.ui.widget.field.constant.FieldConstant;
import fr.sedoo.metadata.client.ui.widget.field.primitive.ListBoxField;
import fr.sedoo.metadata.shared.domain.MetadataDTO;

public class Status extends ListBoxField {

	public Status() {
		super();
		init();
	}

	private void init() {
		listBox.clear();
		listBox.addItem(MetadataMessage.INSTANCE.selectItem(), FieldConstant.UNSELECTED_ID);
		Map<String, String> statusLabels = StatusLabelProvider.getLabels();
		Iterator<Entry<String, String>> iterator = statusLabels.entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry<java.lang.String, java.lang.String> entry = iterator.next();
			listBox.addItem(entry.getValue(), entry.getKey());
		}
	}

	@Override
	public void display(MetadataDTO metadata) {
		ElementUtil.show(label);
		ElementUtil.hide(listBox);
		label.setText(StatusLabelProvider.getLabel(StringUtil.trimToEmpty(metadata.getIdentificationPart().getResourceStatus())));
	}

	@Override
	public void flush(MetadataDTO metadata) {
		if (listBox.getSelectedIndex() == UNSELECTED_ID_INDEX) {
			metadata.getIdentificationPart().setResourceStatus("");
		} else {
			metadata.getIdentificationPart().setResourceStatus(listBox.getValue(listBox.getSelectedIndex()));
		}
	}

	@Override
	public void edit(MetadataDTO metadata) {
		ElementUtil.show(listBox);
		ElementUtil.hide(label);
		String aux = StringUtil.trimToEmpty(metadata.getIdentificationPart().getResourceStatus());
		if (aux.length() > 0) {
			selectByValue(aux);
		} else {
			listBox.setSelectedIndex(UNSELECTED_ID_INDEX);
		}
	}

}
